package com.smtlive.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.smtlive.domain.Role;
import com.smtlive.domain.SmtGrantedAuthority;
import com.smtlive.domain.SmtUserDetails;
import com.smtlive.domain.User;
import com.smtlive.repository.UserRepository;
import com.smtlive.repository.UserRoleRepository;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@Autowired
	UserRepository userRepository;
	
	@Autowired
	UserRoleRepository userRoleRepository;

	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		User user = userRepository.findByUserName(userName);
		if(user != null){
			Collection<Role> roles = userRoleRepository.findRoles(user.getUserId());
			Collection<SmtGrantedAuthority>  grantedAuthorities = new ArrayList<SmtGrantedAuthority>();
			for (Role role : roles) {
				grantedAuthorities.add(new SmtGrantedAuthority(role));
			}
			return new SmtUserDetails(user, grantedAuthorities);
		}			
		return null;
	}
	
}
